package userserv

import (
	"codedef"
	"encoding/json"
	"log"
	"net/http"
)

func convertSpeed2Pwm(speed string) int {
	switch speed {
	case "1":
		return 630
	case "2":
		return 800
	case "3":
		return 980
	case "4":
		return 270
	default:
		return 0
	}
}

func setSwitch(w http.ResponseWriter, r *http.Request) {
	type SetSwitchAction struct {
		Cid    string `json:"cid"`
		Switch string `json:"switch"`
		Speed  string `json:"speed"`
	}

	var uniqueId string
	uniqueId = r.Header.Get("uniqueId")

	log.Printf("setSwitch, uniqueId:%s\n", uniqueId)

	message := make([]byte, r.ContentLength)
	n, _ := r.Body.Read(message)
	if n != int(r.ContentLength) {
		log.Println("setSwitch failed, can't read request body")
		replyError(w, codedef.ERR_REQUEST_INVALID_PARAM)
		return
	}

	log.Println(string(message))

	var action SetSwitchAction
	err := json.Unmarshal(message, &action)
	if err != nil {
		log.Println("setSwitch failed, json decode failed:", err)
		replyError(w, codedef.ERR_DECODE)
		return
	}

	errCode := checkDevCtrlAction(action.Cid, uniqueId)
	if errCode != codedef.ERR_SUCCEED {
		log.Println("setSwitch failed, check task error:", err)
		replyError(w, codedef.ERR_OPRATION_FAILD)
		return
	}

	type Message struct {
		Uri    string `json:"uri"`
		Action string `json:"action"`
		Pwm    int    `json:"pwm"`
	}

	msg := Message{}
	msg.Uri = "/power"
	msg.Action = action.Switch

	if action.Switch == "on" {
		// maxPwm_int := GetMaxPwm(w, action.Cid)
		// if maxPwm_int == -1 {
		//     msg.Pwm = 5555 / 3
		// }
		// msg.Pwm = maxPwm_int / 3
		msg.Pwm = 630
		// msg.Pwm = convertSpeed2Pwm(action.Speed)
	}

	log.Println("message: ", msg)

	controller := getOnlineControllerById(action.Cid)
	if controller == nil {
		log.Println("syncPlan2Device failed, no online controller for:", action.Cid)
		replyError(w, codedef.ERR_CONTROLLER_OFFLINE)
		return
	}

	if controller.isBusy() {
		log.Println("syncPlan2Device failed, controller is busy:", action.Cid)
		replyError(w, codedef.ERR_CONTROLLER_BUSY)
		return
	}

	if wait := syn2Device(*controller, msg); wait != nil {
		//log.Println("start to reply app.", string(wait))

		devMessage, errCode := parserDevReply(wait)
		if 0 != errCode {
			replyError(w, codedef.ERR_OPRATION_FAILD)
		}

		if action.Switch == "off" {
			//
			// TODO::remember the fan speed when the work mode is normal.If is sleep/auto mode, remember maxpwm/3
			//
		}

		replyBuffer(w, devMessage)
		//go GetRuntimeInfo(w, controller)
	} else {
		log.Println("save setSwitch failed, error:", err)
		replyError(w, codedef.ERR_CONTROLLER_NO_RESPONSE)
		return
	}

	//replyJSON(w, map[string]string{"status":"200",})
}

func init() {
	myMux.muxHandlers.HandleFunc("/setSwitch", setSwitch)
}
